package com.xxx.ware.ware_manage_sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxx.ware.ware_manage_sys.bean.entity.records.WmsErrRecord;
import com.xxx.ware.ware_manage_sys.bean.event.Event;
import com.xxx.ware.ware_manage_sys.bean.event.EventProducter;
import com.xxx.ware.ware_manage_sys.mapper.WmsErrRecordMapper;
import com.xxx.ware.ware_manage_sys.service.IErrRecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class ErrRecordServiceImpl extends ServiceImpl<WmsErrRecordMapper, WmsErrRecord> implements IErrRecordService {

    @Autowired
    private EventProducter eventProducter;

    public Boolean saveErrRecord(WmsErrRecord wmsErrRecord){
        //获取最大版本异常记录
        WmsErrRecord lastVersionRecord = getMaxVersionErrRecord(wmsErrRecord.getRecordId(), wmsErrRecord.getOptModule());
        //记录不存在时，初始化1
        if (lastVersionRecord == null) {
            wmsErrRecord.setErrVersion(1);
        } else {
            //记录存在时，版本加1
            wmsErrRecord.setErrVersion(lastVersionRecord.getErrVersion() + 1);
        }
        log.info("待添加异常记录：{}", wmsErrRecord);
        return save(wmsErrRecord);
    }

    @Override
    public void handleErrRecordMsg(String recordId, String optModule) {
        WmsErrRecord errRecord = getMaxVersionErrRecord(recordId, optModule);
        String topic = errRecord.getErrTopic();
        String message = errRecord.getErrMsg();
        Event event  =new Event();
        event.setTopic("err_" + topic);
        event.setMsg(message);
        log.info("待发送的异常消息：{}", event);
        //发送Kafka
        eventProducter.sendKafkaMsg(event);
        log.info("异常消息已发送Kafka");
    }

    private WmsErrRecord getErrRecordBySoleKey(String recordId, String optModule, Integer errVersion){
        LambdaQueryWrapper<WmsErrRecord> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(WmsErrRecord::getRecordId, recordId);
        queryWrapper.eq(WmsErrRecord::getOptModule, optModule);
        queryWrapper.eq(WmsErrRecord::getErrVersion, errVersion);
        return getOne(queryWrapper);
    }

    private WmsErrRecord getMaxVersionErrRecord(String recordId, String optModule){
        LambdaQueryWrapper<WmsErrRecord> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(WmsErrRecord::getRecordId, recordId);
        queryWrapper.eq(WmsErrRecord::getOptModule, optModule);
        queryWrapper.orderByDesc(WmsErrRecord::getErrVersion)
                .last("LIMIT 1");
        return getOne(queryWrapper);
    }
}
